﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace DotnetCore.Module
{
    public class DcModuleCollection : List<DcModuleInfo>
    {
        public Type StartupModuleType { get; }
        public DcModuleCollection(Type startupModuleType)
        {
            StartupModuleType = startupModuleType;
        }


        public TModule GetModule<TModule>() where TModule : DcModule
        {
            var module = this.FirstOrDefault(m => m.Type == typeof(TModule));
            if (module == null)
            {
                throw new Exception("Can not find module for " + typeof(TModule).FullName);
            }
            return (TModule)module.Instance;
        }

        public static void EnsureStartupModuleToBeLast(List<DcModuleInfo> modules, Type startupModuleType)
        {
            var startupModuleIndex = modules.FindIndex(m => m.Type == startupModuleType);
            if (startupModuleIndex >= modules.Count - 1)
            {
                //It's already the last!
                return;
            }

            var startupModule = modules[startupModuleIndex];
            modules.RemoveAt(startupModuleIndex);
            modules.Add(startupModule);
        }

    }
}
